/**
 * Created by hiibook on 2017/6/16.
 */
var wechatMsgConstruct = require('./wechatMsgConstruct');
var config = require('../config/config');
module.exports = function (req, res, next) {
    console.log('使用礼品码');
    if (req.wechatMsg.MsgType == "text") {
        switch (true) {
            case /[0-9A-Z]{32}/.test(req.wechatMsg.Content):
                console.log('接受命令');
                giftCode(req, res, next);
                break;
            default:
                next();
                break;
        }
    } else {
        next()
    }

    function giftCode(req, res, next) {
       var code = decipher('aes-256-cbc','yinxulai',req.wechatMsg.Content);
        var founder = code.split('-')[0];//礼品码创建人
        var flow = code.split('-')[1];//礼品码流量
        var time = code.split('-')[2];//礼品码到期时间
      var encrypted = cipher('aes-256-cbc','yinxulai',req.wechatMsg.Content);
        var chat = {
            Type: "text",
            Content: "原文:"+ req.wechatMsg.Content +
                "加密后："+encrypted+
                "解密后："+decipher('aes-256-cbc','yinxulai',encrypted)
        };
        // 最后一步需要信息,并关闭数据库连接
        req.mysqlConnection.end();
        res.send(wechatMsgConstruct(req.wechatMsg, chat));
    }

};















var crypto = require('crypto');

//加密
var cipher = function(algorithm, key, buf) {
    var encrypted = "";
    var cip = crypto.createCipher(algorithm, key);
    encrypted += cip.update(buf, 'binary', 'hex');
    encrypted += cip.final('hex');
    return encrypted
};


//解密
var  decipher = function(algorithm, key, encrypted) {
    var decrypted = "";
    var decipher = crypto.createDecipher(algorithm, key);
    decrypted += decipher.update(encrypted, 'hex', 'binary');
    decrypted += decipher.final('binary');
    return decrypted
};